package cn.fxl.org.service.impl;


import cn.fxl.basic.service.impl.BasicServiceImpl;
import cn.fxl.basic.utils.Md5Utils;
import cn.fxl.basic.utils.StrUtils;
import cn.fxl.org.domain.Employee;
import cn.fxl.org.mapper.EmployeeMapper;
import cn.fxl.org.service.IEmployeeService;
import cn.fxl.user.domain.Logininfo;
import cn.fxl.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import java.util.List;

@Service
public class EmployeeServiceImpl extends BasicServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    @Transactional
    public void save(Employee employee) throws MessagingException {
        String complexRandomString = StrUtils.getComplexRandomString(32);
        String password = employee.getPassword();
        String md5Psd = Md5Utils.encrypByMd5(complexRandomString + password);
        employee.setSalt(complexRandomString);
        employee.setPassword(md5Psd);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        super.save(employee);
        employeeMapper.saveEmployyeRole(employee);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        Employee employee = employeeMapper.getOne(id);
        logininfoMapper.remove(employee.getLogininfo_id());
        super.remove(id);
        employeeMapper.removeEmployyeRoleById(id);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        String password = employee.getPassword();
        String complexRandomString = StrUtils.getComplexRandomString(32);
        String md5pad = Md5Utils.encrypByMd5(complexRandomString+password);
        employee.setSalt(complexRandomString);
        employee.setPassword(md5pad);
        Employee ogEmployee = employeeMapper.getOne(employee.getId());
        Logininfo ogLogininfo = logininfoMapper.getOne(ogEmployee.getLogininfo_id());
        BeanUtils.copyProperties(employee,ogLogininfo);
        //Copy会将emp的id赋值给Logininfo的id需要在copy后重新赋值id
        ogLogininfo.setId(ogEmployee.getLogininfo_id());
        logininfoMapper.update(ogLogininfo);
        super.update(employee);
        employeeMapper.removeEmployyeRoleById(employee.getId());
        employeeMapper.saveEmployyeRole(employee);
    }

    @Override
    public List<Employee> getEmpByShopId(Long id) {
      return employeeMapper.getEmpByShopId(id);
    }
}
